<?php

class ApplicationController extends AbstractController
{

  public function dispatch()
  {
    return $this->forward($this->request->route());
  }

  public function forward($route)
  {
    $this->response(new Response());

    $params = Simplify::router()->parse($route);

    $this->request()->get()->copyAll($params);

    $Controller = Controller::factory($params);

    $Controller->request($this->request);
    $Controller->response($this->response);
    $Controller->router($this->router);

    $Controller->initialize();

    $action = $this->request->get('action', 'index');

    $output = $Controller->callAction($action);

    if ($output === Response::AUTO) {
      $this->response->setLayout($Controller->getLayout());
      $this->response->setTemplate($Controller->getTemplate());
      $output = $this->response->render(false);
    }
    elseif (is_a($output, 'IView')) {
      $output->setLayout($Controller->getLayout());
      $output = $output->render();
    }

    $this->response->output($output);

    return $output;
  }

}
